//
//  FWQQHuLianAuthHandler.m
//  FWShare
//
//  Created by 范文青 on 14-6-14.
//  Copyright (c) 2014年 fwq. All rights reserved.
//

#import "FWQQHuLianAuthHandler.h"
#import "FWShareValues.h"
#import "FWShare.h"
#import "FWURLQuery.h"
#import "FWAccountProcotol.h"
#import "FWQQHLAuthParam.h"
#import "NSMutableURLRequest+FWHTTPAddition.h"
#import "FWQQHLAccessTokenParam.h"
#import "FWAccessToken.h"
#import "FWQQHLGetUserInfoParam.h"
#import "FWAuthUser.h"
#import "BBlock.h"

@implementation FWQQHuLianAuthHandler

- (FWQQHLAuthParam *)authParam
{
    FWQQHLAuthParam  *param = [FWQQHLAuthParam new];
    [param setClient_id:[[[FWShare shareCenter] accounts] QQHuLianAppId]];
    [param setRedirect_uri:[[[FWShare shareCenter] accounts] QQHuLianRedirectUrl]];
    return param;
}

- (FWQQHLAccessTokenParam *)accessTokenParam:(NSString *)code
{
    FWQQHLAccessTokenParam *param = [FWQQHLAccessTokenParam new];
    [param setClient_id:[[[FWShare shareCenter] accounts] QQHuLianAppId]];
    [param setRedirect_uri:[[[FWShare shareCenter] accounts] QQHuLianRedirectUrl]];
    [param setCode:code];
    [param setClient_secret:[[[FWShare shareCenter] accounts] QQHuLianAppKey]];
    return param;
}
- (FWQQHLGetUserInfoParam *)getUserInfoParam:(FWAccessToken *)token
{
    FWQQHLGetUserInfoParam  *param = [FWQQHLGetUserInfoParam new];
    [param setOpenid:token.uid];
    [param setAccess_token:token.access_token];
    [param setOauth_consumer_key:[[[FWShare shareCenter] accounts] QQHuLianAppId]];
    return param;
}
- (void)getUserInfo:(FWAccessToken *)token
{
    FWQQHLGetUserInfoParam *param = [self getUserInfoParam:token];
    NSMutableURLRequest *request = [NSMutableURLRequest httpRequestWithURL:[NSURL URLWithString:@"https://graph.qq.com/user/get_user_info"] parameters:[param dictionaryRepresentation] headers:nil httpMethod:FWHTTPMethodGET contentType:FWPostContentTypeNone];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue new] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        [BBlock dispatchOnMainThread:^{
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            if ([self isValid:dic]) {
                FWAuthUser  *user = [FWAuthUser instanceQQHL:dic];
                [user setToken:token];
                [user setUid:token.uid];
                [user save];
                if (self.authController.authSuccess) {
                    self.authController.authSuccess(user,self.authController.platform);
                }
            }
        }];
    }];
}
- (void)getOpenID:(FWAccessToken *)token
{
    NSDictionary *dic = @{@"access_token": token.access_token};
    NSMutableURLRequest  *request = [NSMutableURLRequest httpRequestWithURL:[NSURL URLWithString:@"https://graph.qq.com/oauth2.0/me"] parameters:dic headers:nil httpMethod:FWHTTPMethodGET contentType:FWPostContentTypeNone];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue new] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        [BBlock dispatchOnMainThread:^{
            NSString  *responseStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSString  *str1 = [[responseStr componentsSeparatedByString:@"callback("] objectAtIndex:1];
            NSString  *str2 = [[str1 componentsSeparatedByString:@");"] objectAtIndex:0];
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:[str2 dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil];
            if ([self isValid:dic]) {
                NSString  *openid = [dic objectForKey:@"openid"];
                [token setUid:openid];
                [self getUserInfo:token];
            }
        }];
    }];
}
- (void)getAccessToken:(NSString *)code
{
    FWQQHLAccessTokenParam  *param = [self accessTokenParam:code];
    NSMutableURLRequest *request = [NSMutableURLRequest httpRequestWithURL:[NSURL URLWithString:@"https://graph.qq.com/oauth2.0/token"] parameters:[param dictionaryRepresentation] headers:nil httpMethod:FWHTTPMethodPOST contentType:FWPostContentTypeForm];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue new] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        [BBlock dispatchOnMainThread:^{
            NSString  *responseStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            if ([self isValid:responseStr]) {
                FWURLQuery  *query = [[FWURLQuery alloc] initWithQuery:responseStr];
                NSString  *access_token = [query get:@"access_token"];
                NSString  *expires_in = [query get:@"expires_in"];
                FWAccessToken *token = [FWAccessToken instanceQQHuLian:nil accessToken:access_token];
                double expires = [expires_in doubleValue] + [[NSDate date] timeIntervalSince1970];
                [token setExpires_in:[NSString stringWithFormat:@"%.0f",expires]];
                [token setRemind_in:expires_in];
                [self getOpenID:token];
            }
        }];
    }];
}
- (void)startAuth:(FWAuthViewController *)authController
{
    self.authController = authController;
    NSMutableURLRequest  *request = [NSMutableURLRequest httpRequestWithURL:[NSURL URLWithString:@"https://graph.qq.com/oauth2.0/authorize"] parameters:[[self authParam] dictionaryRepresentation] headers:nil httpMethod:FWHTTPMethodGET contentType:FWPostContentTypeNone];
    [authController.authWebView setDelegate:self];
    [authController.authWebView loadRequest:request];
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *urlString = [[request URL] description];
    if ([urlString hasPrefix:[[[FWShare shareCenter] accounts] QQHuLianRedirectUrl]]) {
        FWURLQuery  *query = [[FWURLQuery alloc] initWithURL:[request URL]];
        NSString  *code = [query get:@"code"];
        [self getAccessToken:code];
        return NO;
    }
    return YES;
}

- (BOOL)isValid:(id)obj{
    //取accesstoken时错误处理
    if ([obj isKindOfClass:[NSString class]]) {
        if ([obj hasPrefix:@"callback("]) {
            if (self.authController.authFailed) {
                self.authController.authFailed(nil,self.authController.platform);
            }
            return NO;
        }
    }
    if ([obj isKindOfClass:[NSDictionary class]]) {
        //取userinfo时候错误处理
        if ([[obj objectForKey:@"ret"] intValue] != 0) {
            int code = [[obj objectForKey:@"ret"] intValue];
            NSString  *msg = [obj objectForKey:@"msg"];
            NSError  *error = [NSError errorWithDomain:@"FWQQHLAuthError" code:code userInfo:@{@"message": msg}];
            if (self.authController.authFailed) {
                self.authController.authFailed(error,self.authController.platform);
            }
            return NO;
        }
        
        //取openid时候错误处理
        if ([obj objectForKey:@"error"] != nil) {
            int code = [[obj objectForKey:@"error"] intValue];
            NSString  *message = [obj objectForKey:@"error_description"];
           NSError  *error =  [NSError errorWithDomain:@"FWQQHLAuthError" code:code userInfo:@{@"message": message}];
            if (self.authController.authFailed) {
                self.authController.authFailed(error,self.authController.platform);
            }
            return NO;
        }
    }
    return YES;
}
@end
